from datetime import datetime, timedelta, timezone
from jose import jwt
from sqlalchemy.orm import Session
import bcrypt
from app.db.models.user import User
from app.services.user import UserService
from app.core.config import Settings

# 已移除 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

class AuthService:
    @staticmethod
    def hash_password(password: str) -> str:
        # 直接使用bcrypt库
        salt = bcrypt.gensalt()
        hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
        return hashed.decode('utf-8')

    @staticmethod
    def verify_password(plain_password: str, hashed_password: str) -> bool:
        # 直接使用bcrypt库验证密码
        return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))

    @staticmethod
    def authenticate_user(
        db: Session, 
        email: str, 
        password: str
    ) -> User | None:#表示返回User类型的对象实例，或者返回None
        user = UserService.get_user_by_email(db, email)
        if not user:
            return None
        if not AuthService.verify_password(password, user.password):
            return None
        return user

    @staticmethod
    def authenticate_user_by_nickname(
        db: Session, 
        nickname: str, 
        password: str
    ) -> User | None:
        user = db.query(User).filter(User.nickname == nickname).first()
        if not user:
            return None
        if not AuthService.verify_password(password, user.password):
            return None
        return user

    @staticmethod
    def create_access_token(data: dict) -> str:
        to_encode = data.copy()
        expire = datetime.now(timezone.utc) + timedelta(hours=2)
        to_encode.update({"exp": expire})
        return jwt.encode(
            to_encode, 
            Settings.SECRET_KEY,
            algorithm=Settings.ALGORITHM
        )